/*
 * @Author: wangwei wwdqq7@qq.com
 * @Date: 2025-03-31 17:03:00
 * @LastEditors: wangwei wwdqq7@qq.com
 * @LastEditTime: 2025-04-01 17:07:22
 * @FilePath: /FullStack/pro/typeorm-mysql/src/app.module.ts
 * @Description: --
 */
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
import * as dotenv from 'dotenv';
import * as Joi from 'joi';

import { AuthModule } from '@/auth/auth.module';
import { DatabaseAccess } from '@/entity/DatabaseAccess';
import { Permission } from '@/entity/Permission';
import { Role } from '@/entity/Role';
import { RolePermission } from '@/entity/RolePermission';
import { TableAccess } from '@/entity/TableAccess';
import { User } from '@/entity/User';
import { UserRole } from '@/entity/UserRole';
import { ConfigEnum } from '@/enum/config.enum';
import { UserModule } from '@/user/user.module';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      load: [() => dotenv.config({ path: '.env' })],
      envFilePath: `.env.${process.env.NODE_ENV || ''}`,
      // @sort-keys: reversed
      validationSchema: Joi.object({
        NODE_ENV: Joi.string()
          .valid('development', 'production')
          .default('development'),
        DB_PORT: Joi.number().default(3306),
        DB_HOST: Joi.string().ip().default('localhost'),
        DB_TYPE: Joi.string().valid('mysql', 'postgres').default('mysql'),
        DB_DATABASE: Joi.string().default('test'),
        DB_USERNAME: Joi.string().default('root'),
        DB_PASSWORD: Joi.string().default('root'),
        DB_SYNC: Joi.boolean().default(false),
      }),
    }),

    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) =>
        ({
          type: configService.get(ConfigEnum.DB_TYPE),
          host: configService.get(ConfigEnum.DB_HOST),
          port: configService.get(ConfigEnum.DB_PORT),
          username: configService.get(ConfigEnum.DB_USERNAME),
          password: configService.get(ConfigEnum.DB_PASSWORD),
          database: configService.get(ConfigEnum.DB_DATABASE),
          entities: [
            User,
            Permission,
            Role,
            UserRole,
            TableAccess,
            DatabaseAccess,
            RolePermission,
          ],
          synchronize: configService.get(ConfigEnum.DB_SYNC),
          logging: process.env.NODE_ENV === 'development',
        }) as TypeOrmModuleOptions,
    }),
    AuthModule,
    UserModule,
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}
